﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Xml;
using System.Xml.Serialization;
using VideoReflector.Models;

namespace VideoReflector.Converters
{
    /// <summary>
    /// Generic Value Converter which converts the serialized XML of an object collection to
    /// the corresponding CLR object collection
    /// </summary>
    /// <typeparam name="T"> Type of object in collection to deserialize </typeparam>
    public class XmlCollectionDeserializeConverter<T> : ConverterWithMarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                var nodeCollection = value as System.Collections.IList;
                var objectCollection = new List<T>();
                var serializer = new XmlSerializer(typeof(T));
                foreach (XmlNode node in nodeCollection)
                {
                    objectCollection.Add((T)serializer.Deserialize(new XmlNodeReader(node)));
                }
                return objectCollection;
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    // XAML does not currently support generics therefore derive empty non-generic instances

    [ValueConversion(typeof(System.Collections.IList), typeof(ImageResolution))]
    public class ResolutionCollectionConverter : XmlCollectionDeserializeConverter<ImageResolution> { }

    [ValueConversion(typeof(System.Collections.IList), typeof(Codec))]
    public class CodecCollectionConverter : XmlCollectionDeserializeConverter<Codec> { }
}
